import logging

from poker_bot.core.models.dto import UserDTO
from poker_bot.core.models.dto.user import UserWithDepositsDTO
from poker_bot.core.models.enums.user import LangCode, UserRole
from poker_bot.database.uow import SQLAlchemyUoW
from poker_bot.domain.user import UserEntity

logger = logging.getLogger(__name__)


class UserService:
    def __init__(self, uow: SQLAlchemyUoW):
        self._uow = uow

    async def get_user_by_id(self, user_id: int) -> UserWithDepositsDTO | None:
        """Получаем пользователя по id"""

        return await self._uow.user_reader.get_user_by_id(user_id)

    async def get_user_by_telegram_id(
        self, user_tg_id: int
    ) -> UserWithDepositsDTO | None:
        """Получаем пользователя по telegram id"""

        return await self._uow.user_reader.get_user_by_tg_id(user_tg_id)

    async def get_all_users(self) -> list[UserDTO]:
        """Получаем всех пользователей"""

        return await self._uow.user_reader.get_users()

    async def get_users_with_role(self, user_role: UserRole) -> list[UserDTO]:
        """Получаем пользователей с ролью"""

        return await self._uow.user_reader.get_users_with_role(user_role)

    async def get_user_by_account_account_id(self, account_id: int) -> UserDTO | None:
        """Получаем пользователя по номеру аккаунта"""

        return await self._uow.user_reader.get_user_by_account_account_id(account_id)

    async def update_user_is_subscribed(
        self, user_tg_id: int, is_subscribed: bool = True
    ) -> None:
        user: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        user.update_is_subscribed(is_subscribed)

        await self._uow.user_repo.update_user(user)

        await self._uow.commit()

    async def change_user_lang(self, user_tg_id: int, lang_code: LangCode) -> None:
        """Изменяем язык пользователя"""

        user: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        user.change_lang(lang_code)

        await self._uow.user_repo.update_user(user)

        await self._uow.commit()

    async def change_selected_account(
        self, user_tg_id: int, selected_account_id: int
    ) -> None:
        """Изменяем выбранный аккаунт"""

        user: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        user.update_selected_account_id(selected_account_id)

        await self._uow.user_repo.update_user(user)

        await self._uow.commit()

    async def add_referral(self, user_tg_id: int, referral_tg_id: int) -> None:
        """Добавляем реферала пользователю"""

        user: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        referral: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(
            referral_tg_id
        )
        referral.referrer_id = user.id
        # user.referrals.append(referral)

        # await self._uow.user_repo.update_user(user)
        await self._uow.user_repo.update_user(referral)

        await self._uow.commit()

    async def create_user(self, telegram_id: int, username: str) -> None:
        """Создаем пользователя"""

        user = UserEntity.create(telegram_id=telegram_id, username=username)
        try:
            await self._uow.user_repo.create_user(user)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()
